var GRAVITY  = 9.81;
var ALTITUDEIASTOTAS = 15240;

var isDocked;
var isVisible = true;

 $(document).ready(function(){

		function loadMain()
		{
			
			System.Gadget.onUndock = checkState;
			System.Gadget.onDock = checkState;
			
			checkState();
		}
		
		function checkState()
		{
			if (!System.Gadget.docked)
			{
				undockedState();
			}
			else
			{
				dockedState();
			}
		}
		
		
	   $("#btnCalcBombRelease").click(function(event){
			if(!$("input[type=text]").val()){
				alert('You Must Enter A Plane IAS and Altitude');
			}
			else
			{
				
				$("#BombAngle").val(CalculateAngle( $("#BombIAS").val(),$("#BombALT").val()));
			}
		});
		
		$("input[type=text]").keydown(function(event) {
			if ( event.keyCode == 46 || event.keyCode == 8|| event.keyCode == 9|| event.keyCode == 13 ) {
				
            // let it happen, don't do anything
			}
			else {
				// Ensure that it is a number and stop the keypress
				if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
					event.preventDefault(); 
				}   
			}
		
		});
		
		
		$("input[type=text]").keyup(function(event) {	
				if($("input[type=text]").val()){
					$("#BombAngle").val(CalculateAngle( $("#BombIAS").val(),$("#BombALT").val()));
				}
		});
		function CalculateAngle(bombIAS,bombALT)
		{
			var iasMS = ConvertFromKMPerHourtoMetrePersecond(bombIAS);
			var TAS = ConvertIASToTAS(bombIAS,bombALT);
			var iasDistanceTravelled = CalculateDistanceTravelled(bombIAS,bombALT);
			var iasAngle = RoundToDecimalPlaces(((Math.atan(iasDistanceTravelled/bombALT)) *(180/Math.PI)),2);
						
			return !isNaN(iasAngle) ? iasAngle.toFixed(2) + "%" : "0";

		}
		
		
		
		function CalculateDistanceTravelled(travelSpeed,currentAltitude)
		{
			return ConvertFromKMPerHourtoMetrePersecond(travelSpeed) * Math.sqrt(((currentAltitude*2)/GRAVITY))	
		}

		function ConvertFromKMPerHourtoMetrePersecond(KMPerHour)
		{
			return ((KMPerHour * 1000) / 60 / 60);
		}

		function ConvertTASToIAS( TAS, Altitude )
		{
			return (TAS) / (1 + (Altitude / ALTITUDEIASTOTAS));
		}

		function ConvertIASToTAS( IAS,  Altitude)
		{
			return IAS*(1+ ((Altitude / ALTITUDEIASTOTAS)));
		}
		function RoundToDecimalPlaces(numberToRound,numberOfDecimalPlaces)
		{
			var powerTen=1;
			for(i=1;i<=numberOfDecimalPlaces;i++)
			{
				powerTen = powerTen * 10;
				
			}
			return  (Math.round(numberToRound*powerTen))/powerTen;
		}

     });